package classign.election.kingvar.come.electionclasssign.module.lessonmodule;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;

import java.util.Date;
import java.util.List;

import butterknife.BindView;
import classign.election.kingvar.come.electionclasssign.R;
import classign.election.kingvar.come.electionclasssign.activity.ClassAlbumActivity;
import classign.election.kingvar.come.electionclasssign.module.main.studentmien.StudentMienActivity;
import classign.election.kingvar.come.electionclasssign.adapter.RecyclerAdapter;
import classign.election.kingvar.come.electionclasssign.adapter.RecyclerViewHolder;
import classign.election.kingvar.come.electionclasssign.api.RetrofitService;
import classign.election.kingvar.come.electionclasssign.api.info.AllProjectInfo;
import classign.election.kingvar.come.electionclasssign.api.info.ProTemperature;
import classign.election.kingvar.come.electionclasssign.base.BaseProtocol;
import classign.election.kingvar.come.electionclasssign.broadcastreceiver.TimeChangeReceiver;
import classign.election.kingvar.come.electionclasssign.module.base.BaseActivity;
import classign.election.kingvar.come.electionclasssign.module.main.classmien.classhonor.ClassHonourFragment;
import classign.election.kingvar.come.electionclasssign.tools.bean.User;
import classign.election.kingvar.come.electionclasssign.tools.utils.Constants;
import classign.election.kingvar.come.electionclasssign.tools.utils.DateUtil;
import classign.election.kingvar.come.electionclasssign.tools.utils.SearchEveryDayProjectUtil;
import rx.Subscriber;

/**
 * @author 鞠永强
 * @version $Rev$
 * @time 2017/4/6 0006 10:19
 * @des ${上课模式}
 * @updateAuthor $Author$
 * @updateDate $Date$
 * @updateDes ${TODO}
 */

public class ModeOfAttendanceActivity extends BaseActivity implements View.OnClickListener, TimeChangeReceiver.TimeEvent {
    private static final String TAG = "ModeOfAttendanceActivit";
    TimeChangeReceiver receiver;

    @BindView(R.id.iv_teacher_pic)
    ImageView mIvTeacherPic;  //当前课程老师头像

    @BindView(R.id.tv_current_project_time)
    TextView mTvCurrentProjectTime;  //当期课程时间段

    @BindView(R.id.tv_current_teacher_name)
    TextView mTvCurrentTeacherName;  //当前课程任课教师

    @BindView(R.id.tv_not_num)
    TextView mTvNotNum;  //未到人数

    @BindView(R.id.tv_already_num)
    TextView mTvAlreadyNum;
    @BindView(R.id.tv_year)
    TextView tv_year;  //时间戳

    @BindView(R.id.tv_day)
    TextView tv_day;

    @BindView(R.id.tv_week)
    TextView tv_week;
    @BindView(R.id.tv_schedule)
    TextView tv_schedule; //班级事件

    @BindView(R.id.tv_current_temperature)
    TextView tv_current_temperature;  //当前温度

    @BindView(R.id.tv_today_temperature)
    TextView tv_today_temperature;  //今天温度

    @BindView(R.id.tv_tommorow_temperature)
    TextView tv_tommorow_temperature;  //明天温度

    @BindView(R.id.tv_address)
    TextView tv_address; //定位的位置
    @BindView(R.id.tv_current_project)
    TextView mTvCurrentProject;  //当前课程
    @BindView(R.id.iv_weather_pic)
    ImageView iv_weather_pic; //天气的图片
    @BindView(R.id.iv_class_album)
    ImageView mIvClassAlbum;    //班级相册 首图
    @BindView(R.id.iv_head_pic)
    ImageView mIvHeadPic;  //今日之星 头像
    @BindView(R.id.tv_name)
    TextView tv_name;  //今日之星 名字
    @BindView(R.id.tv_class_name)
    TextView mTvClassName;  //班级名字
    @BindView(R.id.tv_teacher_monitor)
    TextView mTvTeacherMonitor;  //班主任
    @BindView(R.id.rv_current_project)
    RecyclerView mRvCurrentProject;  //今日课程列表
    @BindView(R.id.relative_today_star)
    RelativeLayout mRelativeTodayStar;
    private Fragment classHonourFragment;
    private List mTodayProjectList;
    private RecyclerAdapter mRecyclerAdapter;
    private String detail;
    private int index;
    private String indexString;
    private int totalNum;
    private int shouldNum;
    private int requestNum;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_mode_of_attendance;
    }

    @Override
    protected void initInjector() {
        detail = getIntent().getStringExtra("detail");
        index = getIntent().getIntExtra("index", 0);
        Log.i(TAG, "initInjector: index = " + index);
        totalNum = getIntent().getIntExtra("totalNum", 0);
        shouldNum = getIntent().getIntExtra("shouldNum", 0);
        requestNum = totalNum - shouldNum;
        tv_schedule.setText(detail);
        setDate(System.currentTimeMillis());
        getTemperatureInfoData();
    }


    @Override
    protected void initViews() {

        //注册 时间变化广播接受者
        receiver = new TimeChangeReceiver();
        receiver.setOnTimeEventListener(this);
        registerReceiver(receiver, new IntentFilter(Intent.ACTION_TIME_TICK));

        mRvCurrentProject.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        Glide.with(this).load(BaseProtocol.IMG_BASE + User.getTodayStarLogo(this)).error(R.drawable.default_pic).into(mIvHeadPic);
        tv_name.setText(User.getTodayStarName(this));
        mTvClassName.setText(User.getClassName(this));
        mTvTeacherMonitor.setText("班主任:" + User.getClassTeacherOne(this) + "   班长:" + User.getClassMonitor(this));
        showToDayProject();
        showClassHonour();

    }

    /**
     * 设置时间
     */
    private void setDate(long time) {
        tv_year.setText(DateUtil.getYearByTimeStamp(time) + "年" + DateUtil.getMonthByTimeStamp(time)
                + "月");
        tv_day.setText(DateUtil.getDayByTimeStamp(time) + "");
        tv_week.setText(DateUtil.getWeekOfDate(new Date()));
    }

    /**
     * 显示班级荣誉
     */
    private void showClassHonour() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

        mIvClassAlbum.setOnClickListener(this);
        mRelativeTodayStar.setOnClickListener(this);
        if (classHonourFragment == null) {
            classHonourFragment = ClassHonourFragment.newInstance("classModel");
            fragmentTransaction.add(R.id.framelayout_class_honour, classHonourFragment);
        } else {
            fragmentTransaction.show(classHonourFragment);
        }
        fragmentTransaction.commit();
    }

    /**
     * 显示今天课程
     */
    private void showToDayProject() {
        mTodayProjectList = SearchEveryDayProjectUtil.getCurrentDayProject(DateUtil.getWeekOfDate(new Date()));
        if (mRecyclerAdapter == null) {
            mRecyclerAdapter = new RecyclerAdapter(R.layout.item_current_project, mTodayProjectList) {
                @Override
                protected void onBindData(RecyclerViewHolder holder, int position, Object item) {
                    holder.setText(R.id.tv_duty_name, mTodayProjectList.get(position).toString());
                    holder.setText(R.id.tv_index, position +"");
                    if (position == index+1) {
                        holder.getItemView().setBackgroundResource(R.drawable.bg_color_radius_3);
                    }
                }
            };
            mRvCurrentProject.setAdapter(mRecyclerAdapter);
        } else {
            mRecyclerAdapter.setItemDate(mTodayProjectList);
        }
        mTvCurrentProject.setText(changeString(index) + mTodayProjectList.get(index+1));

    }

    @Override
    protected void updateViews(boolean isRefresh) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_class_album:
                Intent intent = new Intent(this, ClassAlbumActivity.class);
                startActivity(intent);
                break;
            case R.id.relative_today_star:
                intent = new Intent(this, StudentMienActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void getCurrentTime(long time) {
        String currentTime = DateUtil.getHourByTimeStamp(time) + DateUtil.getMinuteTime(time);
        List endTimeList = SearchEveryDayProjectUtil.getCurrentProjectEndTime(DateUtil.getWeekOfDate(new Date()));
        Log.i(TAG, "getCurrentTime: endTimeList =" + endTimeList);
        Log.i(TAG, "getCurrentTime: currentTime =" + currentTime);
        if (endTimeList.size() > 0) {
            for (int i = 0; i < endTimeList.size(); i++) {
                Log.i(TAG, "getCurrentTime: 777777777777 = " + Constants.isProjectModule);
                if (Constants.isProjectModule && currentTime.equals(endTimeList.get(i))) {
                    Constants.isProjectModule = false;
                    finish();
                }
            }
        }

    }

    /**
     * 获取当前温度
     */
    public void getTemperatureInfoData() {
        RetrofitService.getCurrentTemprature(User.getLocation(this))
                .subscribe(new Subscriber<ProTemperature>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e.toString());

                    }

                    @Override
                    public void onNext(ProTemperature proTemperature) {
                        Log.i(TAG, "onNext: proTemperature = " + proTemperature.getStatus());
                        Log.i(TAG, "onNext: proTemperature = getDesc = " + proTemperature.getDesc());
                        if (proTemperature.getStatus() == 1000) {
                            List<ProTemperature.DataEntity.ForecastEntity> forecastEntityList = proTemperature.getData().getForecast();
                            if (forecastEntityList != null) {
                                tv_address.setText(User.getLocation(ModeOfAttendanceActivity.this));
                                tv_current_temperature.setText(proTemperature.getData().getWendu() + "℃");
                                Log.i(TAG, "setTemperatureInfo: size= " + forecastEntityList.get(0).getLow().length());
                                if (forecastEntityList.get(0).getLow().length() == 5) {
                                    tv_today_temperature.setText(forecastEntityList.get(0).getLow().substring(2, 5) + "/" + forecastEntityList.get(0).getHigh().substring(2, 5));
                                    tv_tommorow_temperature.setText(forecastEntityList.get(1).getLow().substring(2, 5) + "/" + forecastEntityList.get(1).getHigh().substring(2, 5));
                                } else {
                                    tv_today_temperature.setText(forecastEntityList.get(0).getLow().substring(2, 6) + "/" + forecastEntityList.get(0).getHigh().substring(2, 6));
                                    tv_tommorow_temperature.setText(forecastEntityList.get(1).getLow().substring(2, 6) + "/" + forecastEntityList.get(1).getHigh().substring(2, 6));
                                }
                                switch (forecastEntityList.get(0).getType()) {
                                    case "晴":
                                        iv_weather_pic.setImageResource(R.drawable.weather_one);
                                        break;
                                    case "多云":
                                        iv_weather_pic.setImageResource(R.drawable.weather_three);
                                        break;
                                    case "中到大雨":
                                        iv_weather_pic.setImageResource(R.drawable.weather_four);
                                        break;
                                    case "大雨":
                                        iv_weather_pic.setImageResource(R.drawable.weather_five);
                                        break;
                                    case "中雨":
                                        iv_weather_pic.setImageResource(R.drawable.weather_nine);
                                        break;
                                    case "雨夹雪":
                                        iv_weather_pic.setImageResource(R.drawable.weather_six);
                                        break;
                                    case "雾霾":
                                        iv_weather_pic.setImageResource(R.drawable.weather_seven);
                                        break;
                                    case "小雨":
                                        iv_weather_pic.setImageResource(R.drawable.weather_two);
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    }
                });
    }

    /**
     * 1,2,3对应转换
     *
     * @param index
     * @return
     */
    private String changeString(int index) {
        List<AllProjectInfo.Entity> entityList = SearchEveryDayProjectUtil.getCurrentTeacherName(DateUtil.getWeekOfDate(new Date()));
        Glide.with(this).load(BaseProtocol.IMG_BASE + entityList.get(index).getLogo())
                .error(R.drawable.default_pic).into(mIvTeacherPic);
        mTvCurrentTeacherName.setText(entityList.get(index).getTname());
        mTvCurrentProjectTime.setText(entityList.get(index).getStart().substring(0,5) + " ～ " + entityList.get(index).getEnd().substring(0,5));
        mTvAlreadyNum.setText("应到:" + totalNum + "  实到:" + shouldNum);
        mTvNotNum.setText("未到 :" + requestNum);
        switch (index) {
            case 0:
                indexString = "当前 : 第一节  ";
                break;
            case 1:
                indexString = "当前 : 第二节  ";
                break;
            case 2:
                indexString = "当前 : 第三节  ";
                break;
            case 3:
                indexString = "当前 : 第四节  ";
                break;
            case 4:
                indexString = "当前 : 第五节  ";
                break;
            case 5:
                indexString = "当前 : 第六节  ";
                break;
            case 6:
                indexString = "当前 : 第七节  ";
                break;
            case 7:
                indexString = "当前 : 第八节  ";
                break;
        }
        return indexString;
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        receiver.removeTimeEventListener();
        unregisterReceiver(receiver);
    }
}
